<template>
  <div id='wrap'>
    <div class="main">
      <!-- 管理系统的头部部分 -->
      <div class="tools-header">
        <button class="openModalBtn" @click="openModal()">Add New Student</button>
        <div>
          <!-- 双向绑定搜索框，即时更新列表 -->
          <input type=" text" name="keyword" class="keyword" placeholder="Search by name" v-model="keyworlds">
          <button class="searchBtn" @click="handleSearch">Search</button>
        </div>
      </div>
      <!-- 管理系统的主体部分 -->
      <table class="studentTable">
        <thead>
          <tr>
            <th><input type="checkbox" class="selectAll"></th>
            <th>ID</th>
            <th>Name</th>
            <th>Gender</th>
            <th>Hobbies</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Age</th>
            <th>Updated At</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <!-- Student rows will be added dynamically here -->
          <!-- !使用v-for渲染本地数据 -->
          <tr v-for="student in filteredStudents" :key="student.id">
            <td><input type="checkbox" class="selectAll" :value="student.id"></td>
            <td>{{ student.id }}</td>
            <td>{{ student.name }}</td>
            <td>{{ student.gender }}</td>
            <td>{{ student.hobbies }}</td>
            <td>{{ student.email }}</td>
            <td>{{ student.phone }}</td>
            <td>{{ student.age }}</td>
            <td>{{ student.create_at }}</td>
            <td>{{ student.update_at }}</td>
            <td>
              <button class="editBtn" data-id="student.id">Edit</button>
              <button class="deleteBtn" data-id="student.id" @click="deleteStudent(student.id)">Delete</button>
            </td>
          </tr>
        </tbody>
      </table>
      <!-- 主题底部 -->
      <div class="studentModal modal" v-show="modal1 === 'block'" @click="closeOpen()">
        <div class="modal-content" @click.stop>
          <h3 class="modalTitle">Add New Student</h3>
          <!-- !监听表单的submit事件，阻止表单的默认提交行为，并将表单内填写的元素提交到本地存储 -->
          <form class="studentForm" @submit.prevent="submitStudentForm">
            <input type="hidden" class="studentIdToEdit">

            <label for="studentName">Name</label>
            <input type="text" name="name" class="studentName" required>

            <label for="studentGender">Gender</label>
            <select name="gender" class="studentGender" required>
              <option value="Male">Male</option>
              <option value="Female">Female</option>
            </select>

            <label for="studentHobbies">Hobbies</label>
            <input type="text" name="hobbies" class="studentHobbies" required>

            <label for="studentEmail">Email</label>
            <input type="email" name="email" class="studentEmail" required>

            <label for="studentPhone">Phone</label>
            <input type="text" name="phone" class="studentPhone" required>

            <label for="studentAge">Age</label>
            <input type="number" name="age" class="studentAge" required>

            <button type="submit" class="saveStudentBtn">Save Student</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang='ts'>
export default {
  name: '学生管理系统',
}
</script>
<script lang='ts' setup>
import { ref, h, type Ref, onMounted, computed } from 'vue';
import { getFormattedCurrentDateTime, validateEmail, validatePhone } from '@/api/api';



//设置响应式数据控制添加页面的显示与隐藏
const modal1 = ref<string>('none');
const keyworlds = ref<string>('');

//封装打开添加页面方法
function openModal() {
  modal1.value = 'block';
}

//封装关闭添加页面方法
function closeOpen() {
  modal1.value = 'none';
}

// 设置响应式数据
const students = ref<Array<{
  id: number;
  name: string;
  gender: string;
  hobbies: string;
  email: string;
  phone: string;
  age: number;
  create_at: string;
  update_at: string;
}>>([]);

//提交学生表单
function submitStudentForm(event: Event) {
  //通过 event.target 获取触发事件的元素
  const form = event.target as HTMLFormElement;
  //创建一个新的formData对象，用来获取form内所有课提交的表单控件的值，并存储在formData对象内
  //在使用 FormData 时，确保表单控件的 name 属性已正确设置，因为 FormData 会根据控件的 name 属性来构建键值对。
  const formData = new FormData(form);
  //创建一个新的学生信息对象
  const newStudent: {
    id: number;
    name: string;
    gender: string;
    hobbies: string;
    email: string;
    phone: string;
    age: number;
    create_at: string;
    update_at: string;
  } = {
    //如果 students 数组不为空，则生成一个新的最大 id 值，否则从 1 开始
    id: students.value.length ? Math.max(...students.value.map(s => s.id)) + 1 : 1,
    //从formData对象内获取对应属性的值
    name: formData.get('name') as string,
    gender: formData.get('gender') as string,
    hobbies: formData.get('hobbies') as string,
    email: formData.get('email') as string,
    phone: formData.get('phone') as string,
    age: parseInt(formData.get('age') as string, 10),
    create_at: getFormattedCurrentDateTime(),
    update_at: getFormattedCurrentDateTime(),
  };
  //将新学生对象添加到 students 数组中。
  students.value.push(newStudent);
  //将 students 数组转换为 JSON 字符串并保存到本地存储中，以便在页面刷新后数据不丢失
  localStorage.setItem('students', JSON.stringify(students.value));
  //关闭模糊框
  closeOpen();
}

// //删除本地学生数据
// function deleteStudent(studentId: number) {
//   //根据学生id查找学生对象在数组中的索引
//   //findIndex()是数组的一个方法，用于查找数组中满足提供的测试函数的第一个元素的索引。如果没有找到，则返回-1。该方法接受一个回调函数作为参数，该回调函数会在数组的每个元素上执行，直到找到第一个使回调函数返回true的元素。
//   //student => student.id === studentId：这是传递给findIndex()方法的回调函数，使用了箭头函数语法。
//   const index = students.value.findIndex(student => student.id === studentId);
//   //如果找到学生对象，则从数组中删除该对象，并更新本地存储中的数据
//   if (index !== -1) {
//     students.value.splice(index, 1);
//     localStorage.setItem('students', JSON.stringify(students.value));
//     localSrudent();
//   }
// }

// 删除学生方法
function deleteStudent(id: number) {
  // 过滤掉要删除的学生
  students.value = students.value.filter(student => student.id !== id);
  // 更新或移除 localStorage 中的数据
  if (students.value.length > 0) {//如果删除数据后students内还有其他数据，则将删除指定数据后的数据保存到本地存储内
    localStorage.setItem('students', JSON.stringify(students.value));
  } else {//如果删除数据之后，students内没有任何数据了，则直接删除students
    localStorage.removeItem('students');
  }
  // Vue 的响应式系统会自动处理 students.value 的变化，无需额外操作
}

//查找学生函数
const filteredStudents = computed(() => {
  if (!keyworlds.value) {
    return students.value; // 如果没有搜索关键词，则返回所有学生
  }
  return students.value.filter(student =>
    student.name.toLowerCase().includes(keyworlds.value.toLowerCase()) || //添加查找姓名的条件
    student.age.toString().includes(keyworlds.value) || //添加查找年龄的条件
    student.gender.toLowerCase().includes(keyworlds.value.toLowerCase()) ||//添加查找性别的条件
    student.id.toString().includes(keyworlds.value) ||// 添加查找ID的条件
    student.phone.toString().includes(keyworlds.value) // 添加查找电话的条件
  ); // 否则，返回匹配搜索关键词的学生
});
function handleSearch() {
  console.log(filteredStudents.value);
}
//获取本地数据
function localSrudent() {
  const data = localStorage.getItem('students');
  console.log(data);
  if (data) {
    //添加本地数据
    students.value = JSON.parse(data);
  } else {
    //如果本地没有数据，则添加默认数据
    students.value = [
      {
        id: 1,
        name: 'Alice',
        gender: 'Female',
        hobbies: 'Reading',
        email: 'alice@example.com',
        phone: '12345678901',
        age: 20,
        create_at: getFormattedCurrentDateTime(),
        update_at: getFormattedCurrentDateTime(),
      },
      {
        id: 2,
        name: 'Bob',
        gender: 'Male',
        hobbies: 'Sports',
        email: 'bob@example.com',
        phone: '10987654321',
        age: 22,
        create_at: getFormattedCurrentDateTime(),
        update_at: getFormattedCurrentDateTime(),
      },
    ];
    console.log(data);
  }
}
// 加载学生数据
onMounted(() => {
  localSrudent();
});

</script>
<style lang='scss'>
.main {
  padding: 20px;

  .tools-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .openModalBtn {
      background-color: #4caf50;
      color: #fff;
      padding: 10px 20px;
      font-size: 16px;
      border-radius: 4px;

      &:hover {
        background-color: #45a049;
      }
    }

    div {
      display: flex;
      align-items: center;

      .keyword {
        padding: 8px;
        font-size: 16px;
        border: 1px solid #ccc;
        border-radius: 4px;
        margin-right: 10px;
      }

      .searchBtn {
        background-color: #2196f3;
        color: #fff;
        padding: 8px 16px;
        font-size: 16px;
        border-radius: 4px;

        &:hover {
          background-color: #1976d2;
        }
      }
    }
  }

  .studentTable {
    width: 100%;
    border-collapse: collapse;
    background-color: #fff;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);

    th,
    td {
      padding: 12px;
      border: 1px solid #ddd;
      text-align: left;
    }

    th {
      background-color: #f2f2f2;
    }

    tr:hover {
      background-color: #f9f9f9;
    }

    button {
      padding: 6px 12px;
      font-size: 14px;
      border-radius: 4px;
      margin-right: 5px;

      &.editBtn {
        background-color: #ff9800;
        color: #fff;

        &:hover {
          background-color: #e68900;
        }
      }

      &.deleteBtn {
        background-color: #f44336;
        color: #fff;

        &:hover {
          background-color: #d32f2f;
        }
      }
    }
  }

  .modal {
    position: fixed;
    z-index: 10;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.4);

    .modal-content {
      background-color: #fff;
      margin: 5% auto;
      padding: 20px;
      border-radius: 4px;
      width: 400px;

      .modalTitle {
        margin-bottom: 20px;
        font-size: 20px;
        text-align: center;
      }

      label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
      }

      input,
      select {
        width: 100%;
        padding: 8px;
        margin-bottom: 15px;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box;
      }

      .saveStudentBtn {
        background-color: #4caf50;
        color: #fff;
        padding: 10px;
        font-size: 16px;
        border-radius: 4px;
        width: 100%;


        &:hover {
          background-color: #45a049;
        }
      }
    }
  }
}
</style>
